package com.dding.cms.base.web;

import java.util.Map;
import java.util.Map.Entry;

import org.dding.core.annotation.Service;
import org.dding.core.log.ILogger;
import org.dding.core.log.LoggerFactory;
import org.dding.core.manager.IServiceManager;
import org.dding.core.system.datasource.DataSource;
import org.dding.core.util.StandaloneXmlParser.DataSourceConfig;
import org.dding.msc.exception.ServiceNotFoundException;
import org.dding.msc.exception.StartException;
import org.dding.msc.exception.StopException;
import org.dding.msc.service.ServiceContainer;
import org.dding.msc.service.ServiceController;
import org.dding.msc.service.ServiceName;
import org.dding.msc.service.StartContext;
import org.dding.msc.service.StopContext;
import org.dding.mvc.ActionSupport;
import org.javalite.activejdbc.DB;
import org.javalite.activejdbc.Registry;

@Service(name = "base.datasource.config")
public class DataSourceAction extends ActionSupport<Object> {

	private ILogger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void start(StartContext startContext)
			throws ServiceNotFoundException, StartException {
		ServiceContainer serviceContainer = startContext.getController()
				.getServiceContainer();
		ServiceController<?> serverConfig = getDataSourceService(serviceContainer);
		if (serverConfig == null) {
			int i = 3;
			try {
				do {
					Thread.sleep(2000);
					logger.info("wait datasource service");
					serverConfig = getDataSourceService(serviceContainer);
					if (serverConfig != null)
						break;
				} while (--i > 0);
				initDB(serverConfig);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		} else {
			initDB(serverConfig);
		}

	}

	// TODO:关闭数据源
	@Override
	public void stop(StopContext context) throws StopException {
		super.stop(context);
	}

	private ServiceController<?> getDataSourceService(
			ServiceContainer serviceContainer) {
		ServiceController<?> serverConfig = serviceContainer
				.getService(ServiceName.of(IServiceManager._SYSTEM_SERVICE
						+ "datasource"));
		return serverConfig;
	}

	// TODO:只能支持default数据源
	private void initDB(ServiceController<?> serverConfig) {
		@SuppressWarnings("unchecked")
		Map<DataSourceConfig, DataSource> map = (Map<DataSourceConfig, DataSource>) serverConfig
				.getValue();
		for (Entry<DataSourceConfig, DataSource> entry : map.entrySet()) {
			if ("default".equals(entry.getKey().name)) {
				new DB("default").open(entry.getValue().getDatasource());
				Registry.instance().init("default");
			}
		}
	}
}
